package video

import (
	"gitee.com/mootok/mootok/src/constant/strings"
	"gitee.com/mootok/mootok/src/models"
	"gitee.com/mootok/mootok/src/storage/database"
	"gitee.com/mootok/mootok/src/utils/logging"
	"gitee.com/mootok/mootok/src/web/api"
	"gitee.com/mootok/mootok/src/web/common/response"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"net/http"
)

func (*ApiVideoImpl) ListUsersVideo(c *gin.Context, userId int, params api.ListUsersVideoParams) {
	pageNo := params.PageNo
	pageSize := params.PageSize
	offset := (pageNo - 1) * pageSize

	logger := logging.LogService("Video.ListUsersVideo").WithFields(logrus.Fields{
		"target_user_id": userId,
		"page_size":      params.PageNo,
		"page_no":        pageNo,
	})

	var videos []models.Video

	result := database.Client.Where("user_id = ?", userId).Order("id").
		Limit(pageSize).Offset(offset).Find(&videos)

	if err := result.Error; err != nil {
		logger.Errorf("retrieve user video result failed:%v", err)
		response.FailWithMsg(c, http.StatusInternalServerError, strings.DataBaseSelectErrorCode, strings.InternalServiceError)
		return
	}

	var count int64
	result.Count(&count)
	pageCount := count / int64(pageSize)
	if pageCount%int64(pageSize) != 0 {
		pageCount++
	}

	items := make([]api.VideoInfo, len(videos))

	if err := Service.ToVideoInfo(videos, &userId, &items); err != nil {
		logger.Errorf("convert video info failed:%v", err)
		response.FailWithMsg(c, http.StatusInternalServerError, strings.DataBaseSelectErrorCode, strings.InternalServiceError)
		return
	}

	response.SuccessWithDetail(c, strings.SuccessCode, strings.Success, &api.VideoPagedListResp{
		PageNo:    &pageNo,
		PageSize:  &pageSize,
		PageCount: &pageCount,
		Count:     &count,
		Items:     &items,
	})

	logger.Info("success")
}
